import {contentModel } from "../../mongodb/db";
import { Content } from "../../entities/content";
import moment from 'moment'

export class ContentServers {
    public static async add (content: {}): Promise<Content | string[]> {
        //将平面对象转换为content实体类
        const newObj = Content.transformerThis(content);
        //验证
        const validateArr = await newObj.validatorClass();
        //添加
        if(validateArr.length !== 0) {
            return validateArr;
        }

        return await contentModel.create(content)
    }

    public static async find(id: string) {
        return await contentModel.findById(id)
    }

    public static async findMore(m: {}) {
        // 将平面对象转换为content实体类
        const newObj = Content.transformerThis(m);
        // 验证
        const validateArr = await newObj.validatorClass(true)
        // 添加
        if(validateArr.length !== 0) {
            return {
                err: validateArr,
                data: [],
                count: 0
            };
        };
        const queryData = await contentModel.find({
            class: {$regex: new RegExp(newObj.class)}
        }).sort({time: -1})

        const count = await contentModel.find({
            class: {$regex: new RegExp(newObj.class)}
        }).countDocuments();

        const total = await contentModel.find({}).countDocuments();

        //处理首页的统计数据
        let elevenDays: {time: string, value: number}[] = [];  // 前11天的数据
        let rateArr: {}[] = [];

        // 为了求第一天的比率，多循环一天的数据
        for(let i=10; i>=0;i--){
            let lastDays = moment().add(-i, 'days').format('YYYY-MM-DD').toString();
            const timeCount = await contentModel.find({
                time: {$regex: new RegExp(lastDays)}
            }).countDocuments();
            elevenDays.push({time: lastDays, value: timeCount})
        }
        
        // //计算比率
        // const rate = () => {
        elevenDays.map((item, index, ele) => {
            if(index === 0) {
                return;
            }

            let aRate: number;
            if(item.value !== 0 && ele[index-1].value === 0){
                aRate = -1
            } else if(item.value === 0 && ele[index-1].value === 0) {
                aRate = 0
            } else{
                aRate = (item.value - ele[index-1].value)/(ele[index-1].value)
            }
            
            rateArr.push({value: aRate, status: aRate})
        })
        // }

        //处理返回数据
        let resData:any[] = [];
        queryData.map(item=>{
            let obj = {
                comment: item.comment, 
                _id: item._id,
                data: '',
                title: item.title,
                class: item.class,
                author: item.author,
                description: item.description,
                time: item.time
            };
            resData.push(obj);
        })
       
        switch(newObj.purpose) {
            case 'getNum':
                return {
                    count
                }
            case 'getData':
                return {
                    err: [],
                    data: resData, 
                    count,
                   
                }
            case 'getTotalData':
                return {
                    total
                }
            case 'getTimeNum':
                const data = elevenDays.slice(1)
                return {
                    data,
                    rateArr,
                    total
                }
            default:;
        }      
   }

   public static async edit(id: string, content: {}) {
    //将平面对象转换为movie实体类
    const newObj = Content.transformerThis(content);
    //验证
    const validateArr = await newObj.validatorClass(true);
    //添加
    if(validateArr.length !== 0) {
        return validateArr;
    }
    return await contentModel.updateOne({_id: id}, content)
}
}


// ContentServers.findMore({time: '2021-10-24 ', purpose: 'getTimeNum'}).then((res) => {
//     console.log(res); 
// })